#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System;
using System.Runtime.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;

namespace AbstractClass.Extensions
{
    /// <summary>
    ///  Provides a set of extension methods for COM type classes.
    /// </summary>
    public static class COMExtensions
    {
        /// <summary>
        /// Converts a <see cref="System.Runtime.InteropServices.ComTypes.FILETIME"/> object to a <see cref="DateTime"/> object.
        /// </summary>
        /// <param name="filetime">The <see cref="System.Runtime.InteropServices.ComTypes.FILETIME"/> object to convert.</param>
        /// <returns>A <see cref="DateTime"/> object equivalent to <paramref name="filetime"/>.</returns>
        public static DateTime ToDateTime(this FILETIME filetime)
        {
            IntPtr buf = IntPtr.Zero;
            try
            {
                var longArray = new long[1];
                int cb = Marshal.SizeOf(filetime);
                buf = Marshal.AllocHGlobal(cb);
                Marshal.StructureToPtr(filetime, buf, false);
                Marshal.Copy(buf, longArray, 0, 1);
                return DateTime.FromFileTime(longArray[0]);
            }
            finally
            {
                if (buf != IntPtr.Zero) Marshal.FreeHGlobal(buf);
            }
        }
    }
}